package com.example.service.Impl;


import com.example.Domain.Operate;
import com.example.Domain.User;
import com.example.Mapper.UserMapper;
import com.example.Util.AliyunMailUtil;
import com.example.Util.MD5;
import com.example.Util.SmsRandomCodeUtil;
import com.example.common.ServerResponse;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userDao;

    @Override
    public ServerResponse<String> generateCheckCode(String email) {
        synchronized (this){
            //邮箱非空验证
            if(email==null||"".equals(email)){
                return ServerResponse.createByACCOUNTError("邮箱不能为空,请填入有效地址");
            }
            //生成随机的6位数字验证码
            String verificationCode= SmsRandomCodeUtil.generateRandomSixNum();
            //调用邮箱发送
            boolean status= AliyunMailUtil.sendMail(email,"直播虚拟仿真实验项目用户注册","您的验证码为："+verificationCode+"。此验证码三分钟内有效，请及时注册。"+"<br><br>"+"本邮件是系统自动发送的，请勿直接回复！感谢您的注册，祝您使用愉快！");
//            SmsPojo smsPojo = new SmsPojo();
//            smsPojo.setToAddress(email);
//            smsPojo.setSubject("用户注册");
//            smsPojo.setContent("注册码为："+verificationCode);
//            if(SmsUtil.sendTextMail(smsPojo)){
            //发送成功保存邮箱地址对应的验证码 todo 已解决
            // redis中保存邮箱验证码三分钟 todo 解决安全 一个email对应唯一的验证码
//            Map<String,String> map = new HashMap<>();
//            map.put(email,verificationCode);
//                  redisTemplate.opsForHash().putAll("email",map);
            if(status){
                redisTemplate.boundValueOps("email_"+email).set(verificationCode,180, TimeUnit.SECONDS);
                // todo 发送的验证码拼接了之前的验证码？？ 获取content内容时候出现getContent现象
                // todo 2019年8月28日09:23:18 接口中屏蔽验证码
                return ServerResponse.createBySuccess();
            } else{
                return ServerResponse.createByACCOUNTError("邮件发送失败");
            }
        }
    }

    @Override
    public ServerResponse<String> forgetSendEmailCode(String email) {
        //验证邮箱是否存在
        int resultCount = userDao.checkEmail(email);
        if(resultCount != 1){
            return ServerResponse.createByErrorMsg("邮箱不存在！");
        }
        //邮箱非空验证
        if(email==null||"".equals(email)){
            return ServerResponse.createByErrorMsg("邮箱不能为空,请填入有效地址");
        }
        //生成随机的验证码
        String verificationCode= SmsRandomCodeUtil.generateRandomSixNum();
        //调用邮箱发送
        try{
            boolean status= AliyunMailUtil.sendMail(email,"直播虚拟仿真实验项目密码重置","您的验证码为："+verificationCode+"。此验证码三分钟内有效，请及时重置密码。"+"<br><br>"+"本邮件是系统自动发送的，请勿直接回复！");
            if(status){
                //发送成功保存邮箱地址对应的验证码 todo 3分钟 已解决
                redisTemplate.boundValueOps("forget_"+email).set(verificationCode,180,TimeUnit.SECONDS);
                return ServerResponse.createBySuccess();
            }else{
                return ServerResponse.createByErrorMsg("邮件发送失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("邮件发送失败");
        }

    }

    @Override
    public ServerResponse<String> updatePassword(User userVo) {
        String checkCode = (String) redisTemplate.boundValueOps("forget_"+userVo.getEmail()).get();
        if(!userVo.getCheckCode().equals(checkCode)){
            return ServerResponse.createByErrorMsg("验证码错误");
        }
//        if(!userVo.getPassword().equals(userVo.getConfirmPassword())){
//            return ServerResponse.createByErrorMsg("密码不一致，请重新输入");
//        }
        User user = new User();
        user.setEmail(userVo.getEmail());
        user.setPassword(MD5.md52(userVo.getPassword()));
        int effectNum = userDao.updatePasswordByEmail(user);
        //通过邮箱获取到用户的用户名、角色
        User u = userDao.checkLogin(user.getEmail());
        Operate operate=new Operate();
        operate.setOperateStyle("用户修改密码");
        operate.setOperateUser(u.getUsername());
        if(u.getRoleid()==1){
            operate.setOperateRoot("管理员");
        }else if(u.getRoleid()==2){
            operate.setOperateRoot("教师");
        }else if(u.getRoleid()==3){
            operate.setOperateRoot("评审账户");
        }else if(u.getRoleid()==4){
            operate.setOperateRoot("学生");
        }
        operate.setOperateStatus("成功");
        userDao.insertOperate(operate);
        if(effectNum == 1 ){
            //将时间赋值
            userDao.upDatePasswordTime(u.getLoginName());
            return ServerResponse.createBySuccessMsg("更新密码成功");
        }
        return ServerResponse.createByErrorMsg("更新密码失败");
    }
}
